package com.datatools.ui.frame;

import com.datatools.entity.*;
import com.datatools.i18n.BaseTextResource;
import com.datatools.ui.basewindow.BaseWindow;
import com.datatools.ui.sqledit.SQLEditPanel;
import com.datatools.util.SerializationUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class LeftPanel extends JPanel implements Serializable {
    private static final long serialVersionUID = 1L;

    private BaseTextResource baseTextResource = BaseTextResource.getInstance();
    //左边面板树
    private JTree dbConTree;

    private static volatile LeftPanel leftPanel;

    public static LeftPanel getInstance() {
        if (null == leftPanel) {
            synchronized (LeftPanel.class) {
                if (null == leftPanel) {
                    leftPanel = new LeftPanel();
                    //先从反序列化文件中读取对象
                    LeftPanelTreeNode root = (LeftPanelTreeNode) SerializationUtil.readObject(LeftPanelTreeNode.class.getName());
                    if (null == root) {
                        root = new LeftPanelTreeNode("我的连接", 0);
                    }
                    JTree jTree = new JTree(root);
                    //解决JTree组件因TreeUI未实现序列化接口，导致无法序列化
                    jTree.setUI(new DbConTreeUI());

                    leftPanel.setDbConTree(jTree);
                }
            }
        }
        return leftPanel;
    }

    private LeftPanel() {
    }

    //防止反序列化破坏单例
    public Object readResolve() {
        return getInstance();
    }

    public void buildGUI() {
        //左面板
        this.setLayout(new BorderLayout());
        //左面板边框
        //Border border = BorderFactory.createLineBorder(Color.green);
        //this.setBorder(border);
        //选项卡
        JTabbedPane dataBaseTabPane = new JTabbedPane();
        dataBaseTabPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        //选项卡-添加数据库-主面板
        JPanel databasePane = new JPanel();
        databasePane.setLayout(new BorderLayout());
        //添加数据库面板工具栏
        JToolBar databaseToolbar = new JToolBar();
        JButton newConnectBtn = new JButton("新建连接");
        JButton refersh = new JButton("刷新连接");
        JButton addSqlEditBtn = new JButton("新建查询");
        refersh.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                connectionDatabase(null);
                dbConTree.repaint();
            }
        });
        newConnectBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                CreateConnectionDialog createConnectionDialog = new CreateConnectionDialog();

                //当Dialog关闭后获取用户输入
                if (null != createConnectionDialog.getConnectionInfoEntity()) {
                    connectionDatabase(createConnectionDialog.getConnectionInfoEntity());
                }
            }
        });
        addSqlEditBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                BaseWindow baseWindow = BaseWindow.getInstance();
                //右面板
                RightPanel rightPanel = baseWindow.getRightPanel();
                //向右面板添加Tab组件
                JPanel compontPanel = new JPanel();
                compontPanel.setLayout(new BorderLayout());
                SQLEditPanel sqlEditPanel = new SQLEditPanel();
                sqlEditPanel.getSqlEditToolBar().setSqlEditPanel(sqlEditPanel);
                compontPanel.add(sqlEditPanel, BorderLayout.CENTER);
                rightPanel.add(compontPanel);
                //为当前添加的Tab组件定制可关闭的 标题
                rightPanel.addTabCloseTitle(compontPanel);

            }
        });
        databaseToolbar.add(newConnectBtn);
        databaseToolbar.add(refersh);
        databaseToolbar.add(addSqlEditBtn);
        databasePane.add(databaseToolbar, BorderLayout.NORTH);

        //树控件事件
        //1.鼠标事件
        LeftPanelTreeMouseAdapter leftPanelTreeMouseAdapter = new LeftPanelTreeMouseAdapter();
        leftPanelTreeMouseAdapter.setSource(dbConTree);
        dbConTree.addMouseListener(leftPanelTreeMouseAdapter);
//        //2.选中事件
        LeftPanelTreeSelectionListener leftPanelTreeSelectionListener = new LeftPanelTreeSelectionListener();
        leftPanelTreeSelectionListener.setSource(dbConTree);
        dbConTree.addTreeSelectionListener(leftPanelTreeSelectionListener);

        JScrollPane dbConScrollPane = new JScrollPane(dbConTree);
        databasePane.add(dbConScrollPane, BorderLayout.CENTER);

        dataBaseTabPane.addTab("数据库", databasePane);

        //左面板-SQL选项卡
        JPanel sqlPanel = new JPanel();
        sqlPanel.setLayout(new BorderLayout());
        JToolBar sqlToolbar = new JToolBar();
        JButton addSqlFileBtn = new JButton("新建SQL文件");
        addSqlFileBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("新建SQL脚本...");
            }
        });
        sqlToolbar.add(addSqlFileBtn);
        sqlPanel.add(sqlToolbar, BorderLayout.NORTH);
        dataBaseTabPane.addTab("脚本", sqlPanel);

        this.add(dataBaseTabPane, BorderLayout.CENTER);


        addSqlEditBtn.doClick();
    }

    //刷新连接
    public void refereshConection() {

    }


    /**
     * 新建连接
     *
     * @param connectionInfoEntity level1节点保存的userObj对象，ConnectionInfoEntity实体类
     */
    public void connectionDatabase(ConnectionInfoEntity connectionInfoEntity) {
        //将当前连接节点添加到根节点
        LeftPanelTreeNode root = (LeftPanelTreeNode) leftPanel.dbConTree.getModel().getRoot();
        LeftPanelTreeNode level1ConNode = new LeftPanelTreeNode(connectionInfoEntity, 1);
        root.add(level1ConNode);
        Connection connection = connectionInfoEntity.getConnection();
        if (null != connection) {
            try {
                DatabaseMetaData metaData = connection.getMetaData();
                //1.遍历数据库
                ResultSet resultSet = metaData.getCatalogs();
                while (resultSet.next()) {
                    LocalSchema localSchema = new LocalSchema();
                    localSchema.setCatalog(resultSet.getString("TABLE_CAT"));
                    //数据库节点
                    LeftPanelTreeNode level2SchemaNode = new LeftPanelTreeNode(localSchema, 2);
                    //表父节点
                    LeftPanelTreeNode level3TablesNode = new LeftPanelTreeNode(baseTextResource.getTable(), 3);
                    //视图父节点
                    LeftPanelTreeNode level3ViewsNode = new LeftPanelTreeNode(baseTextResource.getView(), 3);
                    //函数父节点
                    LeftPanelTreeNode level3FunctionsNode = new LeftPanelTreeNode(baseTextResource.getFunction(), 3);
                    //过程父节点
                    LeftPanelTreeNode level3ProceduresNode = new LeftPanelTreeNode(baseTextResource.getProcedure(), 3);
                    level2SchemaNode.add(level3TablesNode);
                    level2SchemaNode.add(level3ViewsNode);
                    level2SchemaNode.add(level3FunctionsNode);
                    level2SchemaNode.add(level3ProceduresNode);
                    level1ConNode.add(level2SchemaNode);
                }
                resultSet.close();

//                            //2.catalogs
//                            resultSet = metaData.getCatalogs();
//                            List<String> catalogs = new ArrayList<String>();
//                            while (resultSet.next()){
//                                catalogs.add(resultSet.getString("ABLE_CAT"));
//                            }
////
//                            //3.tableTypes
//                            resultSet = metaData.getTableTypes();
//                            List<String> tableTypes = new ArrayList<String>();
//                            while (resultSet.next()) {
//                                tableTypes.add(resultSet.getString("TABLE_TYPE"));
//                            }
//
//
//                            System.out.println("数据库最大CataLogName长度："+metaData.getMaxCatalogNameLength());
//                            System.out.println("数据库已知的用户: "+ metaData.getUserName());
//                            System.out.println("数据库的系统函数的逗号分隔列表: "+ metaData.getSystemFunctions());
//                            System.out.println("数据库的时间和日期函数的逗号分隔列表: "+ metaData.getTimeDateFunctions());
//                            System.out.println("数据库的字符串函数的逗号分隔列表: "+ metaData.getStringFunctions());
//                            System.out.println("数据库供应商用于 'schema' 的首选术语: "+ metaData.getSchemaTerm());
//                            System.out.println("数据库URL: " + metaData.getURL());
//                            System.out.println("是否允许只读:" + metaData.isReadOnly());
//                            System.out.println(":" + metaData.getExtraNameCharacters());
//                            System.out.println(":" + metaData.getIdentifierQuoteString());
//                            System.out.println(":" + metaData.getNumericFunctions());
//                            System.out.println(":" + metaData.getProcedureTerm());
//                            System.out.println(":" + metaData.getSearchStringEscape());
//                            System.out.println(":" + metaData.getSQLKeywords());
//                            System.out.println(":" + metaData.getTimeDateFunctions());
//
//                            System.out.println("数据库的产品名称:" + metaData.getDatabaseProductName());
//                            System.out.println("数据库的版本:" + metaData.getDatabaseProductVersion());
//                            System.out.println(":" + metaData.getDatabaseMajorVersion());
//                            System.out.println(":" + metaData.getDatabaseMinorVersion());
//
//                            System.out.println("驱动程序的名称:" + metaData.getDriverName());
//                            System.out.println("驱动程序的版本:" + metaData.getDriverVersion());
//                            System.out.println(":" + metaData.getDriverMajorVersion());
//                            System.out.println(":" + metaData.getDriverMinorVersion());
//
//                            System.out.println(":" + metaData.getDefaultTransactionIsolation());
//                            System.out.println(":" + metaData.getJDBCMajorVersion());
//                            System.out.println(":" + metaData.getJDBCMinorVersion());
//                            System.out.println(":" + metaData.getMaxCatalogNameLength());
//                            System.out.println(":" + metaData.getMaxBinaryLiteralLength());
//                            System.out.println(":" + metaData.getMaxCharLiteralLength());
//                            System.out.println(":" + metaData.getMaxColumnNameLength());
//                            System.out.println(":" + metaData.getMaxColumnsInGroupBy());
//                            System.out.println(":" + metaData.getMaxColumnsInIndex());
//                            System.out.println(":" + metaData.getMaxColumnsInOrderBy());
//                            System.out.println(":" + metaData.getMaxColumnsInSelect());
//                            System.out.println(":" + metaData.getMaxColumnNameLength());
//                            System.out.println(":" + metaData.getMaxConnections());
//                            System.out.println(":" + metaData.getMaxColumnsInTable());
//                            System.out.println(":" + metaData.getMaxCursorNameLength());
//                            System.out.println(":" + metaData.getMaxIndexLength());
//                            System.out.println(":" + metaData.getMaxProcedureNameLength());
//                            System.out.println(":" + metaData.getMaxRowSize());
//                            System.out.println(":" + metaData.getMaxSchemaNameLength());
//                            System.out.println(":" + metaData.getMaxStatementLength());
//                            System.out.println(":" + metaData.getMaxStatements());
//                            System.out.println(":" + metaData.getMaxStatements());
//                            System.out.println(":" + metaData.getMaxTableNameLength());
//                            System.out.println(":" + metaData.getMaxTablesInSelect());


            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 获取根节点
     *
     * @return
     */
    public LeftPanelTreeNode getRoot() {
        return (LeftPanelTreeNode) this.dbConTree.getModel().getRoot();
    }

    /**
     * 返回当前节点下的所有儿子节点
     *
     * @param parentNode
     * @return
     */
    public List<LeftPanelTreeNode> getChildNodesForNode(LeftPanelTreeNode parentNode) {
        List<LeftPanelTreeNode> childs = new ArrayList<LeftPanelTreeNode>();
        for (int i = 0; i < parentNode.getChildCount(); i++) {
            childs.add((LeftPanelTreeNode) parentNode.getChildAt(i));
        }
        return childs;
    }

    /**
     * 获取所有一级节节点(连接信息节点)
     *
     * @return
     */
    public List<LeftPanelTreeNode> getAllLevel1ConnectionInfoNode() {
        LeftPanelTreeNode root = (LeftPanelTreeNode) this.dbConTree.getModel().getRoot();
        return getChildNodesForNode(root);
    }

    /**
     * 获取当且节点所在的树中的第二级节点对象
     *
     * @param treeNode
     * @return
     */
    public LeftPanelTreeNode getLevel2(LeftPanelTreeNode treeNode) {
        //根节点 =0 一级节点=1，一次类推
        switch (treeNode.getLevel()) {
            case 0:
                return (LeftPanelTreeNode) treeNode.getNextNode().getNextNode();
            case 1:
                return (LeftPanelTreeNode) treeNode.getNextNode();
            case 2:
                return treeNode;
            case 3:
                return (LeftPanelTreeNode) treeNode.getParent();
            case 4:
                return (LeftPanelTreeNode) treeNode.getParent().getParent();
            case 5:
                return (LeftPanelTreeNode) treeNode.getParent().getParent().getParent();
            case 6:
                return (LeftPanelTreeNode) treeNode.getParent().getParent().getParent().getParent();
        }
        return null;
    }

    /**
     * 获取当前节点所在的树的一级节点
     *
     * @param treeNode
     * @return
     */
    public LeftPanelTreeNode getLevel1(LeftPanelTreeNode treeNode) {
        return (LeftPanelTreeNode) getLevel2(treeNode).getParent();
    }

    /**
     * 获取表的索引
     *
     * @param level4TableNode 表节点，索引是第二个节点，列是第一个子节点
     * @throws SQLException
     */
    public void getTableIndexs(LeftPanelTreeNode level4TableNode) throws SQLException {
        Object localTableObj = level4TableNode.getUserObject();
        if (localTableObj instanceof LocalTable) {
            LocalTable localTable = (LocalTable) localTableObj;
            //获取二级节点中 localSchema对象
            LeftPanelTreeNode level2SchemaNode = getLevel2(level4TableNode);
            LocalSchema localSchema = (LocalSchema) level2SchemaNode.getUserObject();
            //获取一级节点中 ConnectionInfoEntity对象
            LeftPanelTreeNode level1ConNode = getLevel1(level4TableNode);
            ConnectionInfoEntity connectionInfoEntity = (ConnectionInfoEntity) level1ConNode.getUserObject();
            Connection connection = connectionInfoEntity.getConnection();
            ResultSet rsTalbeIndexInfo = connection.getMetaData().getIndexInfo(localSchema.getCatalog(), localSchema.getSchema(),
                    localTable.getTableName(), false, false);
            if (rsTalbeIndexInfo != null) {
                LeftPanelTreeNode level5IndexsNode = null;
                if (level4TableNode.getChildCount() > 1) {
                    level5IndexsNode = (LeftPanelTreeNode) level4TableNode.getChildAt(1);
                } else {
                    level5IndexsNode = new LeftPanelTreeNode(baseTextResource.getIndex(), 5);
                    level4TableNode.add(level5IndexsNode);
                }
                while (rsTalbeIndexInfo.next()) {
                    LocalIndex localIndex = new LocalIndex();
                    localIndex.setTableCat(rsTalbeIndexInfo.getString("TABLE_CAT"));
                    localIndex.setTableSchem(rsTalbeIndexInfo.getString("TABLE_SCHEM"));
                    localIndex.setTableName(rsTalbeIndexInfo.getString("TABLE_NAME"));
                    localIndex.setNonUnique(rsTalbeIndexInfo.getBoolean("NON_UNIQUE"));
                    localIndex.setIndexQualifier(rsTalbeIndexInfo.getString("INDEX_QUALIFIER"));
                    localIndex.setIndexName(rsTalbeIndexInfo.getString("INDEX_NAME"));
                    localIndex.setType(rsTalbeIndexInfo.getShort("TYPE"));
                    localIndex.setOrdinalPosition(rsTalbeIndexInfo.getShort("ORDINAL_POSITION"));
                    localIndex.setColumnName(rsTalbeIndexInfo.getString("COLUMN_NAME"));
                    localIndex.setAscOrDesc(rsTalbeIndexInfo.getString("ASC_OR_DESC"));
                    localIndex.setCardinality(rsTalbeIndexInfo.getLong("CARDINALITY"));
                    localIndex.setPages(rsTalbeIndexInfo.getLong("PAGES"));
                    localIndex.setFilterCondition(rsTalbeIndexInfo.getString("FILTER_CONDITION"));
                    LeftPanelTreeNode level6IndexNode = new LeftPanelTreeNode(localIndex, 6);
                    level5IndexsNode.add(level6IndexNode);
                }
                rsTalbeIndexInfo.close();
            }
        }
    }

    /**
     * 获取当前数据的触发器
     *
     * @param level3TriggersNode
     * @throws SQLException
     */
    public void getTableTrigger(LeftPanelTreeNode level3TriggersNode) throws SQLException {
        Object triggersObj = level3TriggersNode.getUserObject();
        if (triggersObj instanceof String) {
            String triggers = (String) triggersObj;
            if (baseTextResource.getTrigger().equals(triggers)) {
                //获取二级节点中 localSchema对象
                LeftPanelTreeNode level2SchemaNode = getLevel2(level3TriggersNode);
                LocalSchema localSchema = (LocalSchema) level2SchemaNode.getUserObject();
                //获取一级节点中 ConnectionInfoEntity对象
                LeftPanelTreeNode level1ConNode = getLevel1(level3TriggersNode);
                ConnectionInfoEntity connectionInfoEntity = (ConnectionInfoEntity) level1ConNode.getUserObject();
                Connection connection = connectionInfoEntity.getConnection();

                if (connectionInfoEntity.getDbType().equals(DataBaseTypeEnum.MYSQL)) {
                    PreparedStatement statement = connection.prepareStatement("show triggers");
                    ResultSet rsTriggers = statement.executeQuery();
                    if (null != rsTriggers) {
                        while (rsTriggers.next()) {
                            LocalTrigger trigger = new LocalTrigger();
                            // TODO 寻找JDBC API

                            LeftPanelTreeNode level4triggreNode = new LeftPanelTreeNode(trigger, 4);
                            level3TriggersNode.add(level4triggreNode);
                        }
                        rsTriggers.close();
                    }
                    if (statement != null) {
                        statement.close();
                    }
                }
            }
        }
    }

    /**
     * 获取当前数据库的存储过程
     *
     * @param level3ProceduresNode
     * @throws SQLException
     */
    public void getProcedures(LeftPanelTreeNode level3ProceduresNode) throws SQLException {
        Object proceduresObj = level3ProceduresNode.getUserObject();
        if (proceduresObj instanceof String) {
            String procedures = (String) proceduresObj;
            if (baseTextResource.getProcedure().equals(procedures)) {
                //获取二级节点中 localSchema对象
                LeftPanelTreeNode level2SchemaNode = getLevel2(level3ProceduresNode);
                LocalSchema localSchema = (LocalSchema) level2SchemaNode.getUserObject();
                //获取一级节点中 ConnectionInfoEntity对象
                LeftPanelTreeNode level1ConNode = getLevel1(level3ProceduresNode);
                ConnectionInfoEntity connectionInfoEntity = (ConnectionInfoEntity) level1ConNode.getUserObject();
                Connection connection = connectionInfoEntity.getConnection();
                DatabaseMetaData metaData = connection.getMetaData();
                ResultSet rsProcedures = metaData.getProcedures(localSchema.getCatalog(), localSchema.getSchema(), null);
                if (null != rsProcedures) {
                    while (rsProcedures.next()) {
                        LocalProcedure procedure = new LocalProcedure();
                        procedure.setProcedureCat(rsProcedures.getString("PROCEDURE_CAT"));
                        procedure.setProcedureSchem(rsProcedures.getString("PROCEDURE_SCHEM"));
                        procedure.setProcedureName(rsProcedures.getString("PROCEDURE_NAME"));
                        procedure.setRemarks(rsProcedures.getString("REMARKS"));
                        procedure.setProcedureType(rsProcedures.getShort("PROCEDURE_TYPE"));
                        procedure.setSpecificName(rsProcedures.getString("SPECIFIC_NAME"));
                        LeftPanelTreeNode level4ProcedureNode = new LeftPanelTreeNode(procedure, 4);
                        level3ProceduresNode.add(level4ProcedureNode);
                    }
                    rsProcedures.close();
                }
            }
        }
    }

    /**
     * 获取当前数据库下所有的函数
     *
     * @param level3FunctionsNode
     * @throws SQLException
     */
    public void getFunctions(LeftPanelTreeNode level3FunctionsNode) throws SQLException {
        Object functionsObj = level3FunctionsNode.getUserObject();
        if (functionsObj instanceof String) {
            String functions = (String) functionsObj;
            if (baseTextResource.getFunction().equals(functions)) {
                //获取二级节点中 localSchema对象
                LeftPanelTreeNode level2SchemaNode = getLevel2(level3FunctionsNode);
                LocalSchema localSchema = (LocalSchema) level2SchemaNode.getUserObject();
                //获取一级节点中 ConnectionInfoEntity对象
                LeftPanelTreeNode level1ConNode = getLevel1(level3FunctionsNode);
                ConnectionInfoEntity connectionInfoEntity = (ConnectionInfoEntity) level1ConNode.getUserObject();
                Connection connection = connectionInfoEntity.getConnection();
                DatabaseMetaData metaData = connection.getMetaData();
                ResultSet rsFunction = metaData.getFunctions(localSchema.getCatalog(), localSchema.getSchema(), null);
                if (null != rsFunction) {
                    while (rsFunction.next()) {
                        LocalFunction function = new LocalFunction();
                        function.setRemarks(rsFunction.getString("REMARKS"));
                        function.setFunctionCat(rsFunction.getString("FUNCTION_CAT"));
                        function.setFunctionName(rsFunction.getString("FUNCTION_NAME"));
                        function.setFunctionSchem(rsFunction.getString("FUNCTION_SCHEM"));
                        function.setFunctionType(rsFunction.getShort("FUNCTION_TYPE"));
                        function.setSpecificName(rsFunction.getString("SPECIFIC_NAME"));
                        LeftPanelTreeNode level4FunctionNode = new LeftPanelTreeNode(function, 4);
                        level3FunctionsNode.add(level4FunctionNode);
                    }
                    rsFunction.close();
                }
            }
        }
    }

    /**
     * 加载当前数据库下所有的表或视图
     *
     * @param level3TablesOrViewsNode
     * @param tableType               目前只实现："TABLE", "VIEW", 还可以是："SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
     * @throws SQLException
     */
    public void getTables(LeftPanelTreeNode level3TablesOrViewsNode, String tableType) throws SQLException {
        Object tablesOrViewsObj = level3TablesOrViewsNode.getUserObject();
        if (tablesOrViewsObj instanceof String) {
            String tablesOrViews = (String) tablesOrViewsObj;
            if (baseTextResource.getTable().equals(tablesOrViews) || baseTextResource.getView().equals(tablesOrViews)) {
                //获取二级节点中 localSchema对象
                LeftPanelTreeNode level2SchemaNode = getLevel2(level3TablesOrViewsNode);
                LocalSchema localSchema = (LocalSchema) level2SchemaNode.getUserObject();
                //获取一级节点中 ConnectionInfoEntity对象
                LeftPanelTreeNode level1ConNode = getLevel1(level3TablesOrViewsNode);
                ConnectionInfoEntity connectionInfoEntity = (ConnectionInfoEntity) level1ConNode.getUserObject();
                Connection connection = connectionInfoEntity.getConnection();
                DatabaseMetaData metaData = connection.getMetaData();
                //查询当前库下的所有表或视图
                String[] tableTypes = new String[]{tableType};
                ResultSet rsTables = metaData.getTables(localSchema.getCatalog(), localSchema.getSchema(), null, tableTypes);
                if (null != rsTables) {
                    while (rsTables.next()) {
                        LocalTable table = new LocalTable();
                        table.setTableCat(rsTables.getString("TABLE_CAT"));
                        table.setTableSchem(rsTables.getString("TABLE_SCHEM"));
                        table.setTableName(rsTables.getString("TABLE_NAME"));
                        // "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
                        table.setTableType(rsTables.getString("TABLE_TYPE"));
                        table.setRemarks(rsTables.getString("REMARKS"));
                        table.setTypeCat(rsTables.getString("TYPE_CAT"));
                        table.setTypeSchem(rsTables.getString("TYPE_SCHEM"));
                        table.setTypeName(rsTables.getString("TYPE_NAME"));
                        table.setSelfReferencingColName(rsTables.getString("SELF_REFERENCING_COL_NAME"));
                        // Values are "SYSTEM", "USER", "DERIVED". (may be null)
                        table.setRefGeneration(rsTables.getString("REF_GENERATION"));
                        LeftPanelTreeNode level4TableNode = new LeftPanelTreeNode(table, 4);
                        level3TablesOrViewsNode.add(level4TableNode);
                    }
                    rsTables.close();
                }
            }
        }
    }

    /**
     * 获取表下的列
     *
     * @param level4TableNode 表节点，列是第一个子节点，索引是第二个节点，
     * @throws SQLException
     */
    public void getTableColums(LeftPanelTreeNode level4TableNode) throws SQLException {
        Object localTableObj = level4TableNode.getUserObject();
        if (localTableObj instanceof LocalTable) {
            LocalTable localTable = (LocalTable) localTableObj;
            LeftPanelTreeNode level1ConNode = getLevel1(level4TableNode);
            ConnectionInfoEntity connectionInfoEntity = (ConnectionInfoEntity) level1ConNode.getUserObject();
            Connection connection = connectionInfoEntity.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet rsColumn = metaData.getColumns(localTable.getTableCat(), localTable.getTableSchem(), localTable.getTableName(), null);
            if (rsColumn != null) {
                LeftPanelTreeNode level5ColumnsNode = null;
                if (level4TableNode.getChildCount() == 0) {
                    level5ColumnsNode = new LeftPanelTreeNode(baseTextResource.getColumn(), 5);
                    level4TableNode.add(level5ColumnsNode);
                } else {
                    level5ColumnsNode = (LeftPanelTreeNode) level4TableNode.getChildAt(0);
                }

                while (rsColumn.next()) {
                    LocalColumn column = new LocalColumn();
                    column.setTableCat(rsColumn.getString("TABLE_CAT"));
                    column.setTableName(rsColumn.getString("TABLE_NAME"));
                    column.setTableSchem(rsColumn.getString("TABLE_SCHEM"));
                    column.setColumnName(rsColumn.getString("COLUMN_NAME"));
                    column.setDataType(rsColumn.getInt("DATA_TYPE"));
                    column.setTypeName(rsColumn.getString("TYPE_NAME"));
                    column.setTypeName(rsColumn.getString("TYPE_NAME"));
                    column.setDecimalDigits(rsColumn.getInt("DECIMAL_DIGITS"));
                    column.setNumPrecRadix(rsColumn.getInt("NUM_PREC_RADIX"));
                    column.setNullable(rsColumn.getInt("NULLABLE"));
                    column.setRemarks(rsColumn.getString("REMARKS"));
                    column.setColumnDef(rsColumn.getString("COLUMN_DEF"));
                    column.setCharOctetLength(rsColumn.getInt("CHAR_OCTET_LENGTH"));
                    column.setOrdinalPosition(rsColumn.getInt("ORDINAL_POSITION"));
                    column.setIsNullable(rsColumn.getString("IS_NULLABLE"));
                    column.setScopeCatalog(rsColumn.getString("SCOPE_CATALOG"));
                    column.setScopeSchema(rsColumn.getString("SCOPE_SCHEMA"));
                    column.setScopeTable(rsColumn.getString("SCOPE_TABLE"));
                    column.setSourceDataType(rsColumn.getShort("SOURCE_DATA_TYPE"));
                    column.setIsAutoIncrement(rsColumn.getString("IS_AUTOINCREMENT"));
                    column.setIsGeneratedColumn(rsColumn.getString("IS_GENERATEDCOLUMN"));
                    LeftPanelTreeNode level6ColumnNode = new LeftPanelTreeNode(column, 6);
                    level5ColumnsNode.add(level6ColumnNode);
                }
                rsColumn.close();
            }
        }
    }

    public JTree getDbConTree() {
        return dbConTree;
    }

    public void setDbConTree(JTree dbConTree) {
        this.dbConTree = dbConTree;
    }


}
